package com.ruoyi.client.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.client.mapper.NovelRewardsMapper;
import com.ruoyi.client.pojo.form.NovelInsertForm;
import com.ruoyi.client.pojo.vo.NovelRewardsVo;
import com.ruoyi.client.service.NovelRewardsService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.novel.domain.Novels;
import com.ruoyi.novel.mapper.NovelsMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sql.rowset.serial.SerialException;
import java.util.List;

@Service
public class NovelRewardsServiceImpl  implements NovelRewardsService {

    @Resource
    private NovelRewardsMapper novelRewardsMapper;

    @Resource
    private NovelRewardsService novelRewardsService;
    
    @Resource
    private NovelsMapper novelsMapper;


    @Override
    @Transactional
    public Long insert(NovelInsertForm form) {
        // 验证必填字段
        if (form.getNovelId() == null) {
            throw new ServiceException("小说ID不能为空");
        }
        if (form.getMessage() == null || form.getMessage().trim().isEmpty()) {
            throw new ServiceException("评论内容不能为空");
        }
        
        // 获取用户id
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 构建评论对象
        Novels comment = new Novels();
        comment.setUserId(userId);
        comment.setNovelId(form.getNovelId());
        comment.setMessage(form.getMessage());
        comment.setAmount(form.getAmount() != null ? form.getAmount() : 0);
        
        // 设置章节ID
        if (form.getChapterId() != null) {
            comment.setChapterId(form.getChapterId());
        }
        
        // 设置父评论ID，如果parentId为null或0，则设置为0（表示顶级评论）
        if (form.getParentId() != null && form.getParentId() > 0) {
            comment.setParentId(form.getParentId());
        } else {
            comment.setParentId(0L);  // 0表示顶级评论
        }
        
        // 插入评论
        int result = novelRewardsMapper.insert(comment);
        if (result <= 0) {
            throw new ServiceException("添加评论失败");
        }
        
        // 更新小说的评论数 +1
        updateNovelCommentCount(form.getNovelId(), 1);
        
        return comment.getRewardId();
    }

    @Override
    @Transactional
    public Boolean update(NovelInsertForm form) {
        // 用户登录验证
        StpUtil.checkLogin();
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 查询评论是否存在
        NovelRewardsVo commentVo = novelRewardsMapper.selectNovelById(form.getRewardId());
        if (commentVo == null) {
            throw new ServiceException("评论不存在");
        }
        
        // 验证是否是本人的评论
        if (!commentVo.getUserId().equals(userId)) {
            throw new ServiceException("只能修改自己的评论");
        }
        
        // 构建更新对象
        Novels comment = new Novels();
        comment.setRewardId(form.getRewardId());
        comment.setMessage(form.getMessage());
        if (form.getAmount() != null) {
            comment.setAmount(form.getAmount());
        }
        
        return novelRewardsMapper.update(comment) > 0;
    }

    @Override
    public NovelRewardsVo selectNovelById(Long rewardId) {
        // 用户登录验证,未登录会抛出例外NotLoginException
        StpUtil.checkLogin();

        // 查询评论（从视图中查询，带有用户信息）
        NovelRewardsVo novelRewardsVo = novelRewardsMapper.selectNovelById(rewardId);
        if (novelRewardsVo == null) {
            throw new ServiceException("id对应的评论不存在");
        }
        
        return novelRewardsVo;
    }

    @Override
    public List<NovelRewardsVo> selectAll() {
        // 用户登录验证
        StpUtil.checkLogin();
        
        // 查询所有评论
        return novelRewardsMapper.selectAll();
    }

    @Override
    public List<NovelRewardsVo> selectVoMyList(NovelInsertForm form) {
        // 用户登录验证
        StpUtil.checkLogin();
        
        Novels novels = new Novels();
        if (form.getNovelId() != null) {
            novels.setNovelId(form.getNovelId());
        }
        if (form.getUserId() != null) {
            novels.setUserId(form.getUserId());
        }
        if (form.getChapterId() != null) {
            novels.setChapterId(form.getChapterId());
        }
        
        return novelRewardsMapper.selectVoMyList(novels);
    }


    /**
     * 删除评论
     * @param rewardId 评论ID
     * @return 删除结果
     */
    @Override
    @Transactional
    public Boolean deleteById(Long rewardId) {
        // 用户登录验证
        StpUtil.checkLogin();
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 查询评论是否存在
        NovelRewardsVo comment = novelRewardsMapper.selectNovelById(rewardId);
        if (comment == null) {
            throw new ServiceException("评论不存在");
        }
        
        // 验证是否是本人的评论
        if (!comment.getUserId().equals(userId)) {
            throw new ServiceException("只能删除自己的评论");
        }
        
        // 保存小说ID，用于后续更新评论数
        Long novelId = comment.getNovelId();
        
        // 删除评论
        int result = novelRewardsMapper.deleteByPrimaryKey(rewardId);
        if (result > 0) {
            // 更新小说的评论数 -1
            updateNovelCommentCount(novelId, -1);
            return true;
        }
        return false;
    }
    
    /**
     * 更新小说的评论数
     * @param novelId 小说ID
     * @param increment 增量（1表示+1，-1表示-1）
     */
    private void updateNovelCommentCount(Long novelId, int increment) {
        try {
            // 查询小说信息
            Novels novel = novelsMapper.selectNovelsByNovelId(novelId);
            if (novel != null) {
                // 更新评论数
                Long currentCount = novel.getCommentCount();
                if (currentCount == null) {
                    currentCount = 0L;
                }
                long newCount = Math.max(0L, currentCount + increment); // 确保不会变成负数
                
                novel.setCommentCount(newCount);
                novelsMapper.updateNovels(novel);
            }
        } catch (Exception e) {
            // 记录日志但不影响主流程
            System.err.println("更新小说评论数失败: " + e.getMessage());
        }
    }

    /**
     * 点赞评论
     * @param rewardId 评论ID
     * @return 点赞结果
     */
    @Override
    @Transactional
    public Boolean likeComment(Long rewardId) {
        // 用户登录验证
        StpUtil.checkLogin();
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 查询评论是否存在
        NovelRewardsVo comment = novelRewardsMapper.selectNovelById(rewardId);
        if (comment == null) {
            throw new ServiceException("评论不存在");
        }
        
        // 增加点赞数
        int result = novelRewardsMapper.incrementAmount(rewardId);
        return result > 0;
    }

    /**
     * 取消点赞评论
     * @param rewardId 评论ID
     * @return 取消点赞结果
     */
    @Override
    @Transactional
    public Boolean unlikeComment(Long rewardId) {
        // 用户登录验证
        StpUtil.checkLogin();
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 查询评论是否存在
        NovelRewardsVo comment = novelRewardsMapper.selectNovelById(rewardId);
        if (comment == null) {
            throw new ServiceException("评论不存在");
        }
        
        // 减少点赞数
        int result = novelRewardsMapper.decrementAmount(rewardId);
        return result > 0;
    }
}